package co.yixiang.business.visit

import co.yixiang.annotation.AnonymousAccess
import co.yixiang.api.ApiResult
import co.yixiang.entity.Visit
import co.yixiang.entity.VisitRepository
import co.yixiang.util.*
import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

interface VisitService{

    /**
     * 添加来访者
     */
    fun saveVisit(visit: Visit): ApiResult<*>

    /**
     * 获取我的来访者
     */
    fun getMyVisits(pageModel: PageModel): ApiResult<*>

    /**
     * 获取我的来访者数量
     */
    fun getMyVisitsCount(userId: Long?): Int?
}

@Service
@Transactional(rollbackFor = [Exception::class])
open class VisitServiceImp(@Autowired val visitRepository: VisitRepository,
                           @Autowired val userServiceKT: UserServiceKT) : VisitService {

    override fun saveVisit(visit: Visit): ApiResult<*> {

        return visitRepository.save(visit).block().run { getApiResult(200, "保存成功") }
    }

    override fun getMyVisits(pageModel: PageModel): ApiResult<*> {

        return visitRepository.getVisitsByUserIdOrderByCreateTimeDesc(pageModel.userId)
            .toIterable()
            .toMutableList()
            .takeIf { it.isNotEmpty() }?.run {

            toListVo { userServiceKT.getUserInfo(it.visitUserId!!) }
                .toPage(pageModel.page!!, pageModel.pageSize!!)
                .getApiResult(200, "获取我的来访者数据成功")
        } ?: getApiResult(201, "暂无数据")
    }

    override fun getMyVisitsCount(userId: Long?): Int? {

        return visitRepository.getVisitsByUserIdOrderByCreateTimeDesc(userId).toIterable()
            .toMutableList()
            .takeIf { it.isNotEmpty() }?.run {
            toSet().size
        }?: 0
    }
}

@RestController
@RequestMapping("/visit")
class VisitController(@Autowired val visitService: VisitService) {


    @ApiOperation("添加来访者")
    @PostMapping("/saveVisit")
    @AnonymousAccess
    fun saveVisit(visit: Visit): ApiResult<*> = visitService.saveVisit(visit)


    @ApiOperation("获取我的来访者")
    @PostMapping("/getMyVisits")
    @AnonymousAccess
    fun getMyVisits(pageModel: PageModel): ApiResult<*> = visitService.getMyVisits(pageModel)

}


